/**
 * @author 黄淮杰
 */

// 添加离开页面事件，提示用户是否离开页面
window.addEventListener("beforeunload", leave);

function leave(e) {
    let event = window.event || e;
    event.returnValue = null;
}

/********************初始化开始***********************/
// 定义的全局变量
let questionList = $("#question-list");
let simpleTemplate = $("#simple-template").innerHTML;
let multipleTemplate = $("#multiple-template").innerHTML;
let textTemplate = $("#text-template").innerHTML;
let simpleItemTemplate = $("#simple-item-template").innerHTML;
let multipleItemTemplate = $("#multiple-item-template").innerHTML;
let chooseDeadline = $("#choose-deadline");
let questionTitle = $("#question-title");
let questionId = getQueryVariable("id");
let questionnaires = getDataFromLocal("questionnaires");
let questions = [];

// 初始化日期选择和问卷标题的值或内容为空
chooseDeadline.value = "";
questionTitle.value = "";

// 判断当前状态是新建问卷还是编辑问卷
let questionnaireStatus;
if (questionId === -1) {
    questionnaireStatus = "new";
} else {
    questionnaireStatus = "edit";
    // 获取问题列表
    questions = deepClone(questionnaires[questionId - 1].list);
    // 渲染问卷
    renderQuestionnaire();
}
/********************初始化结束***********************/

// 点击“添加问题”按钮，下滑显示问题类型
let hasOpened = false;
$("#edit-question-button").onclick = function () {
    if (hasOpened === false) {
        show("#choose-question-type", "100");
    } else {
        hide("#choose-question-type", "100");
    }
    hasOpened = !hasOpened;
};

/********处理日期选择开始**********/
// 点击选择日期，弹出日历选择组件
chooseDeadline.onfocus = function () {
    chooseDeadline.value = "";
    fadeIn("#calendar", ".3s");
};

// 日期选择错误的提示
function chooseDeadlineError() {
    message("选择的日期不能小于当前日期！");
}

let isSelectingCalendar = false;

// 为日历添加监听器，获取选中的日期
$("#days").addEventListener("click", function (e) {
    isSelectingCalendar = true;
    if (e.target && e.target.nodeName === "LI") {
        let choose_date = e.target.getAttribute("data-date");
        let date = choose_date.split("-");
        let choose_year = Number(date[0]);
        let choose_month = Number(date[1]);
        let choose_day = Number(date[2]);
        let now_date = new Date();
        let now_year = now_date.getFullYear();
        let now_month = now_date.getMonth() + 1;
        let now_day = now_date.getDate();
        // 判断选择的日期是否合法
        if (choose_year < now_year) {
            chooseDeadlineError();
            return;
        }
        if (choose_year === now_year && choose_month < now_month) {
            chooseDeadlineError();
            return;
        }
        if (choose_year === now_year && choose_month === now_month && choose_day < now_day) {
            chooseDeadlineError();
            return;
        }
        // 选择的日期合法，修改输入框的值
        chooseDeadline.value = choose_date;
        // 日历组件隐藏
        fadeOut("#calendar", ".3s");
        isSelectingCalendar = false;
    }
});
/********处理日期选择结束**********/

/*******渲染题目的选项********/
function renderQuestionItemsHtml(data, type) {
    let tmpHtml = "";
    let questionItemsHtml = "";
    data.forEach(item => {
        if (type === "radio") {
            tmpHtml = simpleItemTemplate.replace("{content}", item.content)
                .replaceAll("{id}", item.id);
        }
        if (type === "checkbox") {
            tmpHtml = multipleItemTemplate.replace("{content}", item.content)
                .replaceAll("{id}", item.id);
        }
        questionItemsHtml += tmpHtml;
    });
    return questionItemsHtml;
}

/****渲染题目到页面*****/
function renderQuestions() {
    let tmpHtml = "";
    let questionListHtml = "";
    let questionItemsHtml = "";
    questions.forEach(item => {
        if (item.type === "radio") {
            questionItemsHtml = renderQuestionItemsHtml(item.items, "radio");
            tmpHtml = simpleTemplate.replaceAll("{id}", item.id)
                .replaceAll("{items}", questionItemsHtml)
                .replaceAll("{title}", item.title);
        }
        if (item.type === "checkbox") {
            questionItemsHtml = renderQuestionItemsHtml(item.items, "checkbox");
            tmpHtml = multipleTemplate.replaceAll("{id}", item.id)
                .replaceAll("{items}", questionItemsHtml)
                .replaceAll("{title}", item.title);
        }
        if (item.type === "text") {
            tmpHtml = textTemplate.replaceAll("{id}", item.id)
                .replaceAll("{title}", item.title);
            if (item.necessary === true) {
                tmpHtml = tmpHtml.replaceAll("{checked}", "checked");
            }
        }
        questionListHtml += tmpHtml;
    });
    questionList.innerHTML = questionListHtml;
}

/*******渲染标题******/
function renderTitle() {
    questionTitle.value = questionnaires[questionId - 1].title;
}

/*******渲染截止日期******/
function renderDeadline() {
    chooseDeadline.value = questionnaires[questionId - 1].deadline;
}

/*********渲染问卷到页面********/
function renderQuestionnaire() {
    // 渲染标题
    renderTitle();
    // 渲染问题列表
    renderQuestions();
    // 渲染截止日期
    renderDeadline();
}

/*****处理添加问题*****/
// 插入问题
function insertQuestion(questionId, type) {
    if (questions.length === 10) {
        return message("最多只能添加10条问卷");
    }
    let question;
    let num = questionId + 1;
    if (type === "radio") {
        question = {
            "id": num,
            "type": "radio",
            "title": "",
            "items": [{
                    "id": 1,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                },
                {
                    "id": 2,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                },
                {
                    "id": 3,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                }
            ]
        };
    } else if (type === "checkbox") {
        question = {
            "id": num,
            "type": "checkbox",
            "title": "",
            "items": [{
                    "id": 1,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                },
                {
                    "id": 2,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                },
                {
                    "id": 3,
                    "content": "",
                    "selected": 0,
                    "unselect": 0,
                    "tempSelected": 0,
                    "tempUnselect": 0
                }
            ]
        };
    } else {
        question = {
            "id": num,
            "type": "text",
            "title": "",
            "content": "",
            "necessary": true,
            "sumOfWords": 0,
            "sumOfWordsList": []
        };
    }
    if (questionId === questions.length) {
        questions.push(question);
    } else {
        // 将问题插入到指定位置
        let newQuestions = [];
        questions.forEach((item, index) => {
            if (index < questionId - 1) {
                newQuestions.push(item);
            } else if (index === questionId - 1) {
                newQuestions.push(item);
                newQuestions.push(question);
            } else {
                item.id += 1;
                newQuestions.push(item);
            }
        });
        questions = deepClone(newQuestions);
    }
    renderQuestions();
    let questionItem = $(".question-item")[questionId];
    success(questionItem, 1500);
    fadeInFromDown(questionItem, 30);
}
// 添加单选题
$("#btn-simple").onclick = function () {
    insertQuestion(questions.length, "radio");
};

// 添加多选题
$("#btn-multiple").onclick = function () {
    insertQuestion(questions.length, "checkbox");
};

// 添加文本题
$("#btn-text").onclick = function () {
    insertQuestion(questions.length, "text");
};

// 向上移动问题
function operationUp(id, dataList) {
    if (id === "1") {
        message("不能再上移了！");
    } else {
        // 交换两个问题的位置
        dataList[id - 2].id = Number(id);
        dataList[id - 1].id = Number(id) - 1;
        let prev = dataList[id - 2];
        dataList[id - 2] = dataList[id - 1];
        dataList[id - 1] = prev;
        // 重新渲染
        renderQuestions();
        if (arguments[2] !== "item") {
            let question = $(".question-item");
            let questionItem = question[id - 2];
            let preQuestionItem = question[id - 1];
            success(questionItem, 1000);
            fadeInFromDown(questionItem, 300);
            fadeInFromTop(preQuestionItem, 300);
        }
    }
}

// 向下移动问题
function operationDown(id, dataList) {
    let endId = String(dataList.length);
    if (id === endId) {
        message("不能再下移了！");
    } else {
        // 交换两个问题的位置
        dataList[id].id = Number(id);
        dataList[id - 1].id = Number(id) + 1;
        let prev = dataList[id];
        dataList[id] = dataList[id - 1];
        dataList[id - 1] = prev;
        // 重新渲染
        renderQuestions();
        if (arguments[2] !== "item") {
            let question = $(".question-item");
            let questionItem = question[id];
            let preQuestionItem = question[id - 1];
            success(questionItem, 1000);
            fadeInFromDown(preQuestionItem, 300);
            fadeInFromTop(questionItem, 350);
        }
    }
}

// 复制问题
function operationCopy(id, dataList, type) {
    if (dataList.length === 10 && type !== "item") {
        return message("最多只能添加10条问卷！");
    }
    let newList = [];
    for (let i = 0; i < id; i++) {
        newList.push(dataList[i]);
    }
    newList[id] = deepClone(dataList[id - 1]);
    newList[id].id = Number(id) + 1;
    for (let i = id; i < dataList.length; i++) {
        dataList[i].id += 1;
        newList.push(dataList[i]);
    }
    if (type === "question") {
        questions = deepClone(newList);
    }
    if (type === "item") {
        let questionId = arguments[3];
        questions[questionId - 1].items = deepClone(newList);
    }
    renderQuestions();
    if (type !== "item") {
        let questionItem = $(".question-item")[id];
        success(questionItem, 1000);
        fadeInFromTop(questionItem, 150)
    }
}

// 删除问题
function operationDel(id, dataList, type) {
    if (type === "item" && dataList.length === 2) {
        message("至少保留两个选项");
        return;
    }
    let newList = delAnListItem(dataList, Number(id));
    if (type === "question") {
        questions = deepClone(newList);
    }
    if (type === "item") {
        let questionId = arguments[3];
        questions[questionId - 1].items = deepClone(newList);
    }
    renderQuestions();
}

function operationQuestion(operationName, questionId) {
    if (operationName === "operation-up") {
        operationUp(questionId, questions);
    }
    if (operationName === "operation-down") {
        operationDown(questionId, questions);
    }
    if (operationName === "operation-copy") {
        operationCopy(questionId, questions, "question");
    }
    if (operationName === "operation-del") {
        myConfirm("确认删除？", function () {
            operationDel(questionId, questions, "question");
            message("删除成功！");
        })
    }
    if (operationName === "insert-radio") {
        insertQuestion(Number(questionId), "radio");
    }
    if (operationName === "insert-checkbox") {
        insertQuestion(Number(questionId), "checkbox");
    }
    if (operationName === "insert-text") {
        insertQuestion(Number(questionId), "text");
    }
}

// 绑定事件
questionList.addEventListener("click", function (e) {
    let event = e.target;
    /*********处理问题的“上移”“下移”“复用”“删除”**********/
    if (event.parentElement.parentElement.getAttribute("data-type") === "question-operation") {
        // 获取问题的编号
        let questionId = event.parentElement.parentElement.getAttribute("data-id");
        let operationName = event.parentElement.className;
        operationQuestion(operationName, questionId);
    }

    if (event.parentElement.getAttribute("data-type") === "question-operation") {
        // 获取问题的编号
        let questionId = event.parentElement.getAttribute("data-id");
        let operationName = event.className;
        operationQuestion(operationName, questionId);
    }

    /*********处理问题的插入*************/
    if (event.parentElement.parentElement.getAttribute("data-type") === "insert-list") {
        // 获取问题的编号
        let questionId = event.parentElement.parentElement.getAttribute("data-id");
        let operationName = event.parentElement.getAttribute("data-type");
        operationQuestion(operationName, questionId);
    }

    if (event.parentElement.getAttribute("data-type") === "insert-list") {
        // 获取问题的编号
        let questionId = event.parentElement.getAttribute("data-id");
        let operationName = event.getAttribute("data-type");
        operationQuestion(operationName, questionId);
    }

    /*******处理问题的选项的“上移”“下移”“复用”“删除”******/
    if (event.parentElement.parentElement.getAttribute("data-type") === "item-operation") {
        // 获取问题选项的编号
        let itemId = event.parentElement.parentElement.getAttribute("data-id");
        let questionId = event.parentElement.parentElement.parentElement.getAttribute("data-id");
        let operationName = event.parentElement.className;
        let items = questions[questionId - 1].items;
        if (operationName === "up-question") {
            operationUp(itemId, items, "item");
        }
        if (operationName === "down-question") {
            operationDown(itemId, items, "item");
        }
        if (operationName === "add-question") {
            operationCopy(itemId, items, "item", questionId);
        }
        if (operationName === "del-question") {
            operationDel(itemId, items, "item", questionId);
        }
    }

    if (event.parentElement.className === "question-necessary") {
        let questionId = event.getAttribute("data-id");
        questions[questionId - 1].necessary = event.checked;
    }
})

/*****处理问题的标题和选项输入****/
questionList.addEventListener("keyup", function (e) {
    let event = e.target;

    if (event.className === "question-title") {
        let questionId = event.parentElement.getAttribute("data-id");
        questions[questionId - 1].title = event.value;
    }

    if (event.className === "question-item-input") {
        let itemId = event.getAttribute("data-id");
        let questionId = event.parentElement.parentElement.getAttribute("data-id");
        questions[questionId - 1].items[itemId - 1].content = event.value;
    }
})

/********保存新问卷*********/
function saveNewQuestion(title, status, deadline) {
    let questionnaire = {
        "id": questionnaires.length + 1,
        "title": title,
        "createTime": formatDateTime(new Date()),
        "status": status,
        "deadline": deadline,
        "list": []
    };
    questionnaire.list = deepClone(questions);
    questionnaires.push(questionnaire);
    saveDataToLocal(questionnaires, "questionnaires");
}

/********修改现有问卷*********/
function changeQuestion(title, status, deadline) {
    questionnaires[questionId - 1].title = title;
    questionnaires[questionId - 1].status = status;
    questionnaires[questionId - 1].deadline = deadline;
    questionnaires[questionId - 1].list = deepClone(questions);
    saveDataToLocal(questionnaires, "questionnaires");
}

// 检查问卷是否可以发布
function checkQuestionnaires(deadline) {
    if (deadline === "") {
        message("还没选择截止日期呢！");
        warn(chooseDeadline, 1500);
        return false;
    }
    let flag = true;
    let flag2 = true;
    for (let i = 0; i < questions.length; i++) {
        if (flag2 === false) {
            break;
        }
        let question = questions[i];
        if (question.title.replaceAll(" ", "") === "") {
            message("还有问题尚未填写完整！");
            let questionTitle = $(".question-item")[i];
            questionTitle.scrollIntoView(true);
            warn(questionTitle, 2000);
            flag = false;
            flag2 = false;
            break;
        }
        if (question.type === "text") {
            continue;
        }
        let items = questions[i].items;
        for (let j = 0; j < items.length; j++) {
            if (items[j].content.replaceAll(" ", "") === "") {
                message("还有选项尚未填写完整！");
                let questionItem = $(".question-item")[i];
                questionItem.scrollIntoView(true);
                warn(questionItem, 2000);
                flag = false;
                flag2 = false;
                break;
            }
        }
    }
    return flag;
}

// 保存问卷
function saveQuestionnaire(title, publicStatus, deadline) {
    if (questionnaireStatus === "new") {
        saveNewQuestion(title, publicStatus, deadline);
    }
    if (questionnaireStatus === "edit") {
        changeQuestion(title, publicStatus, deadline);
    }
    location.href = "index.html"
}

// 保存或者发布问卷
function saveOrPublish(publicStatus) {
    let title = questionTitle.value.replaceAll(" ", "");
    let deadline = chooseDeadline.value;
    if (title === "") {
        message("请输入标题！");
        questionTitle.scrollIntoView(false);
        warn(questionTitle, 1500);
        return;
    } else {
        title = questionTitle.value.trim();
    }
    if (questions.length === 0) {
        message("问卷不能为空！");
        warn($("#edit-question-box"), 1500);
        return;
    }
    if (publicStatus === 1) {
        if (!checkQuestionnaires(deadline)) {
            return;
        }
        document.querySelector('#btn-publish').style.display = 'none';
        const confirmPublish = document.querySelector('#btn-confirm-publish');
        confirmPublish.style.display = 'inline-block';
        const timeout = setTimeout(() => {
            document.querySelector('#btn-publish').style.display = 'inline-block';
            confirmPublish.style.display = 'none';
            message("取消发布");
        }, 1500);
        confirmPublish.onclick = () => {
            clearTimeout(timeout);
            window.removeEventListener("beforeunload", leave);
            saveQuestionnaire(title, publicStatus, deadline);
        }
    } else {
        myConfirm("是否保存问卷？", function () {
            window.removeEventListener("beforeunload", leave);
            saveQuestionnaire(title, publicStatus, deadline)
        })
    }
}

// 点击保存按钮
$("#btn-save").onclick = function () {
    saveOrPublish(0);
}

// 点击发布按钮
$("#btn-publish").onclick = () => {
    saveOrPublish(1);
}

// 初始化导航栏特效
headerAnimation();
